package com.mikelouis.test.scala.impatient.chapter16_xml

import java.net.URL

import scala.xml.dtd.{PublicID, DocType}
import scala.xml.parsing.ConstructingParser
import scala.xml.transform.{RuleTransformer, RewriteRule}
import scala.xml._

/**
 * Created by yuazhu on 4/26/2015.
 */
object Chapter16 extends App {
  // 1

  // 2
  val exec2 = <ul>
    <li>Opening bracket: [</li>
    <li>Closing bracket: ]</li>
    <li>Opening brace: {{</li>
    <li>Closing brace: }}</li>
  </ul>
  println(exec2)

  // 3
  // 内嵌表达式中的字符串并不会被转成Text节点而是Atom[String]节点。这和普通的Text节点还是有区别的——Text是Atom[String]的子类
  // if reformat code -> doesn't work
  println(<li>Fred</li> match { case <li>{Text(t)}</li> => t})

  // MatchError here
  //  println(<li>{"Fred"}</li> match { case <li>{scala.xml.Text(t)}</li> => t })

  println(<li>{Text("Fred")}</li> match { case <li>{Text(t)}</li> => t})

  // 4
  val root = XML.load(this.getClass.getClassLoader.getResourceAsStream("test.xhtml"))

  val imgs: NodeSeq = root \\ "img"

  // img \ "@alt " 's type is scala.xml.NodeSeq

  for (img <- imgs if (img \ "@alt").text == "") println(img)

  // 5
  imgs.foreach(x => println(x \ "@src" text))

  // 6
  val aTag:NodeSeq = root \\ "a"
  aTag.foreach(x => println("%s: %s".format(x.child(0).text, x \ "@href" text)))

  // 7
  def genDl(input: Map[String,String]):Elem = <dl>{for((k,v) <- input) yield <dt>{k}</dt><dd>{v}</dd>}</dl>

  println(genDl(Map("A" -> "1", "B" -> "2")))

  // 8
  def dlToMap(input: Elem):Map[String, String] = {
    var map = Map[String, String]()
    val keys = input \ "dt"
    val values = input \ "dd"
    for(i <- 0 until keys.size) map += keys(i).text -> values(i).text
    map
  }

 println(dlToMap(<dl><dt>A</dt><dd>1</dd><dt>B</dt><dd>2</dd></dl>))

  // 9
  def transform(filename: String) {
    val root = XML.loadFile(filename)
    val rule1 = new RewriteRule {
      override def transform(n: Node) = n match {
        case x @ <img/> => if (x.attributes("alt") == null) x.asInstanceOf[Elem] % Attribute(null, "alt", "TODO", scala.xml.Null) else x
        case _ => n
      }
    }
    val transformed = new RuleTransformer(rule1).transform(root)
    scala.xml.XML.save("./src/test_new.xhtml", transformed(0))
  }

  // 10
  def transform2(filename: String) {
    val parser = ConstructingParser.fromFile(new java.io.File(filename), preserveWS = true)
    val doc = parser.document
    val root = doc.docElem
    val rule1 = new RewriteRule {
      override def transform(n: Node) = n match {
        case x @ <img/> => if (x.attributes("alt") == null) x.asInstanceOf[Elem] % Attribute(null, "alt", "TODO", scala.xml.Null) else x
        case _          => n
      }
    }
    val transformed = new RuleTransformer(rule1).transform(root)
    //println(transformed)
    scala.xml.XML.save("./src/cdata_new.xhtml", transformed(0),
      enc = "UTF-8",
      xmlDecl = true,
      doctype = DocType("html",
        PublicID("-//W3C//DTD XHTML 1.0 Strict//EN",
          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"),
        Nil))
  }

}
